package com.bjut.vehicleshow.aop;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.lang.reflect.UndeclaredThrowableException;
import java.sql.SQLException;

/**
 * All rights Reserved, Designed By www.sac.com
 *
 * @author 王文贵
 * @version V1.0.0
 * @projectName 火电代码
 * @title GlobalExceptionHandler
 * @package com.sac.thermal.web.config.aop
 * @description ${TODO}
 * @date 2019/9/12 11:03
 * @copyright 2019 www.sac.com
 * 注意 本内容仅限于国电南自,禁止外泄以及用于其他的商业
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    @Value("${log-environment.isDevelop}")
    private Boolean isDevelop;

    private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 所以未指定异常的处理会进入到此方法
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    ResponseEntity handleException(Exception ex) {
        if (isDevelop) {
            return new ResponseEntity(ex.getMessage()
                    , HttpStatus.INTERNAL_SERVER_ERROR);
        }
        LOGGER.error(ex.getMessage());
        return new ResponseEntity("unknown error"
                , HttpStatus.INTERNAL_SERVER_ERROR);
    }

    /**
     * sql异常
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(SQLException.class)
    @ResponseBody
    ResponseEntity handleSqlException(SQLException ex) {
        LOGGER.error(ex.getMessage());
        return new ResponseEntity("db operation error"
                , HttpStatus.INTERNAL_SERVER_ERROR);
    }


    @ExceptionHandler(UndeclaredThrowableException.class)
    @ResponseBody
    ResponseEntity<?> handleUndeclaredThrowableException(UndeclaredThrowableException ex) {
        LOGGER.error(ex.getMessage());
        return handleException(ex);
    }

    /**
     * 空指针异常
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(NullPointerException.class)
    @ResponseBody
    ResponseEntity handleNullPointException(NullPointerException ex) {
        LOGGER.error(ex.getMessage());
        return new ResponseEntity("空指针异常"
                , HttpStatus.INTERNAL_SERVER_ERROR);
    }


}
